//
//  Level2.m
//  GameProject
//
//  Created by Blair Trusler on 01/12/2011.
//  Copyright (c) 2011 Blair Trusler. All rights reserved.
//

#import "GameHeader.h"
#include <sys/types.h>
#include <sys/sysctl.h>

@implementation Level2Scene
- (id)init{
    //CHANGED LOLOL
    self = [super init];
    if (self) {
        //add tiled map as base layer
        Level2 *backgroundLayer = [Level2 node];
        [self addChild:backgroundLayer z:-1];
        
        //add HUD and sprite(s) ABOVE the tiled map
        HUD *hudLayer = [HUD node];
        [self addChild:hudLayer z:1];
        
        
        Fog *fogLayer = [Fog node];
        [self addChild:fogLayer z:0];
        
    }
    return self;
}
@end

@implementation Level2

@synthesize tileMap = _tileMap;
@synthesize background = _background;
@synthesize foreground = _foreground;
@synthesize meta = _meta;
@synthesize player = _player;
@synthesize playerSprite = _playerSprite;
@synthesize hud = _hud;
@synthesize allowDiags;
@synthesize startX,startY,endX,endY;
@synthesize patrolPointX1, patrolPointY1, patrolPointX2, patrolPointY2;
@synthesize startPatrolX, startPatrolY, endPatrolX, endPatrolY;
@synthesize startPatrolX_enemy3, startPatrolY_enemy3, endPatrolX_enemy3, endPatrolY_enemy3; 
@synthesize startPatrolX_enemy4, startPatrolY_enemy4,endPatrolX_enemy4,endPatrolY_enemy4;
@synthesize startPatrolX_enemy5, startPatrolY_enemy5,endPatrolX_enemy5,endPatrolY_enemy5;


#pragma mark - dealloc
//Release retained objects
- (void) dealloc{
	self.tileMap = nil;
    self.background = nil;
    self.foreground = nil;
    self.player = nil;  
    self.playerSprite = nil;
    self.hud = nil;
	[super dealloc];
}

#pragma mark - scene
+(id) scene{
    //Create scene
	CCScene *scene = [CCScene node];
    
    //Add layer
	Level2 *layer = [Level2 node];
    
	//Add layer as a child of scene
	[scene addChild: layer z:0];
    
    //Add HUD to scene
    HUD *hud = [HUD node];    
    [scene addChild: hud z:2];
    layer.hud = hud;   
    
	return scene;
}


#pragma mark initialize
-(id) init{
	if( (self=[super init] )) {
        
        
        //Disable touch input on this layer:
        self.isTouchEnabled = NO;
        calcPatrolPath = 1;
//        calcPatrolPath = TRUE;
        calcPatrolPath2 = TRUE;
        
        audioCounter = 0;
        isMoving = FALSE;

        if (dPadOn == FALSE){
            //Accelerometer enabled:
            self.isAccelerometerEnabled = YES;
            //Interval at which the hardware delivers the data:
            [[UIAccelerometer sharedAccelerometer] setUpdateInterval: (1.0 / 60)];
        }        
        else {
            self.isAccelerometerEnabled = NO; 
        }
        patrolPathsToGenerate = TRUE;
        pathCheck = 0;
        //Enable Music:
        [AudioManager playLevel2Music];
        
        //Initialize sprite sheet and batch node with .plist and .png files:
        [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"GameSpriteSheet.plist"]; 
        sceneSpriteBatchNode = [CCSpriteBatchNode batchNodeWithFile:@"GameSpriteSheet.png"];  
        
        //Add sprite nodes to background layer: 
        [self addChild:sceneSpriteBatchNode];
        //Load .TMX tiled map //and player sprite//
        [self loadMap];
        
        speedBoost = 0;     //Reset speed booster to 0
        speedBoostTilt=0;
        
        //disable diagonal movement:
        self.allowDiags = NO; 
        
        //Schedule update method (for collision/warp detection)
        [self scheduleUpdate];
        
//        if (patrolPathsToGenerate){
//            [self schedule:@selector(patrolPaths:)interval:1];
//
//        }
//        else{
//            [self schedule:@selector(createPath:) interval:4];//using zero for the interval will just sync us with the default refresh, usually every 1/60 second
//
//        }

        
//        if (([platformType isEqualToString:@"Simulator"])||([platformType isEqualToString:@"iPad"])||([platformType isEqualToString:@"iPad 2 (WiFi)"])||([platformType isEqualToString:@"iPad 2 (GSM)"])||([platformType isEqualToString:@"iPad 2 (CDMA)"])){
//            CCLOG(@"Enabling Lighting");
//
//            CGSize screenSize = [CCDirector sharedDirector].winSize;
//            renderLayer = [CCRenderTexture renderTextureWithWidth:2100 height:2350];
//            renderLayer.position = ccp(screenSize.width/2, screenSize.height/2);
//
//            [[renderLayer sprite] setBlendFunc: (ccBlendFunc) { GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA }];        
//            [self addChild:renderLayer z:0];
//            spotLight = [CCSpotLight initWithRenderTexture:renderLayer spotLightRadius:400.0f renderColor:ccc4(0, 0, 0, 255)];
//            [self addChild:spotLight z:1 tag:999];
//        }
        
        //Schedule pathfinder every 1.5 seconds:
//        [self schedule:@selector(createPath:) interval:4];//using zero for the interval will just sync us with the default refresh, usually every 1/60 second
        CCLOG(@"Update Methods Scheduled");        
    }
    return self;
}


- (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    int kPlayerSpeed = 2;
    float destX, destY;
    BOOL shouldMove = NO;
    float currentX = playerX.position.x;
    float currentY = playerX.position.y;
    oldPosition = ccp(playerX.position.x, playerX.position.y);    
    
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
        
        if(acceleration.x > -0.40 ) {             // tilting the device upwards, move up
            isMoving = TRUE;
            destX = currentX ;
            destY = currentY + (kPlayerSpeed + speedBoostTilt);
            //        [playerX changeState:kStateWalkingUp];
            if (playerX.characterState != kStateCollision){
                //            [playerX changeState:kStateWalkingUp];
                direction = 1;
                shouldMove = YES;
            }
            else{
                shouldMove = NO;
            }        
        } 
        else if (acceleration.x < -0.60) {    // tilting the device down, move down
            isMoving = TRUE;
            destX = currentX ;
            destY = currentY - ( kPlayerSpeed + speedBoostTilt  );
            //        [playerX changeState:kStateWalkingDown];
            if (playerX.characterState != kStateCollision){
                //            [playerX changeState:kStateWalkingDown];
                direction = 2;
                shouldMove = YES;
            }
            else{
                shouldMove = NO;
            }        
        } 
        else if(acceleration.y < -0.05) {     // tilting the device to the right, move right
            isMoving = TRUE;
            destX = currentX + ( kPlayerSpeed + speedBoostTilt);
            destY = currentY ;
            //        [playerX changeState:kStateWalkingRight];
            if (playerX.characterState != kStateCollision){
                //            [playerX changeState:kStateWalkingRight];
                direction = 3;
                shouldMove = YES;
            }
            else{
                shouldMove = NO;
            }        
        } 
        else if (acceleration.y > 0.05) {     // tilting the device to the left, move left
            isMoving = TRUE;
            destX = currentX - (kPlayerSpeed + speedBoostTilt);
            destY = currentY ;
            //        [playerX changeState:kStateWalkingLeft];
            if (playerX.characterState != kStateCollision){
                //            [playerX changeState:kStateWalkingLeft];
                direction = 4;
                shouldMove = YES;
            }
            else{
                shouldMove = NO;
            }  
        } 
        
        else {
            destX = currentX;
            destY = currentY;
            shouldMove = NO;
            isMoving = FALSE;
        }
        if(shouldMove) {
            [playerX setPosition:CGPointMake(destX,destY)];
        }
        else {
            // should stop
            [playerX changeState:kStateIdle];
            direction = 0;
        }
        
        
        
        
    }
    else{
        if(acceleration.x > -0.40 ) {             // tilting the device upwards, move up
            isMoving = TRUE;
            destX = currentX ;
            destY = currentY + (kPlayerSpeed + speedBoostTilt);
            //        [playerX changeState:kStateWalkingUp];
            if (playerX.characterState != kStateCollision){
                //            [playerX changeState:kStateWalkingUp];
                direction = 1;
                shouldMove = YES;
            }
            else{
                shouldMove = NO;
            }        
        } 
        else if (acceleration.x < -0.60) {    // tilting the device down, move down
            isMoving = TRUE;
            destX = currentX ;
            destY = currentY - ( kPlayerSpeed + speedBoostTilt  );
            //        [playerX changeState:kStateWalkingDown];
            if (playerX.characterState != kStateCollision){
                //            [playerX changeState:kStateWalkingDown];
                direction = 2;
                shouldMove = YES;
            }
            else{
                shouldMove = NO;
            }        
        } 
        else if(acceleration.y < -0.15) {     // tilting the device to the right, move right
            isMoving = TRUE;
            destX = currentX + ( kPlayerSpeed + speedBoostTilt);
            destY = currentY ;
            //        [playerX changeState:kStateWalkingRight];
            if (playerX.characterState != kStateCollision){
                //            [playerX changeState:kStateWalkingRight];
                direction = 3;
                shouldMove = YES;
            }
            else{
                shouldMove = NO;
            }        
        } 
        else if (acceleration.y > 0.15) {     // tilting the device to the left, move left
            isMoving = TRUE;
            destX = currentX - (kPlayerSpeed + speedBoostTilt);
            destY = currentY ;
            //        [playerX changeState:kStateWalkingLeft];
            if (playerX.characterState != kStateCollision){
                //            [playerX changeState:kStateWalkingLeft];
                direction = 4;
                shouldMove = YES;
            }
            else{
                shouldMove = NO;
            }  
        } 
        
        else {
            destX = currentX;
            destY = currentY;
            shouldMove = NO;
            isMoving = FALSE;
        }
        if(shouldMove) {
            [playerX setPosition:CGPointMake(destX,destY)];
        }
        else {
            // should stop
            [playerX changeState:kStateIdle];
            direction = 0;
        }
    }
    
}

#pragma mark - camera
//Set camera on player position
-(void)setViewpointCenter:(CGPoint) position {
    
    CGSize winSize = [[CCDirector sharedDirector] winSize];
    
    int x = MAX(position.x, winSize.width / 2);
    int y = MAX(position.y, winSize.height / 2);
    x = MIN(x, (_tileMap.mapSize.width * _tileMap.tileSize.width) - winSize.width / 2);
    y = MIN(y, (_tileMap.mapSize.height * _tileMap.tileSize.height) - winSize.height/2);
    CGPoint actualPosition = ccp(x, y);
    
    CGPoint centerOfView = ccp(winSize.width/2, winSize.height/2);
    CGPoint viewPoint = ccpSub(centerOfView, actualPosition);
    self.position = viewPoint;    
    
}

#pragma mark - map
//Generates game map, spawn positions and initiates path start and end points
-(void)loadMap{
    CCLOG(@"Loading Tiled Map...");     //CCLOG instead of "NSLog" - unlike NSLog, CCLOG does not run on "release" builds, hence improving performance. 
    
    NSString *mapname = [Level2 getDefaultLevel]; //Sets ".tmx" file name as string 
    
    [[CCDirector sharedDirector] setProjection:CCDirectorProjection2D];     //Sets projection to 2D mode, removes bug with black lines/gaps between certain tiles when camera scrolling
    
    //Load .tmx file: 
    self.tileMap = [CCTMXTiledMap tiledMapWithTMXFile:mapname]; //Uses Level_1.tmx as level to load
    
    //Load map layers from tmx:
    self.background = [_tileMap layerNamed:@"Background"];
    self.foreground = [_tileMap layerNamed:@"Foreground"];  //Foreground items eg rocks, weapons etc
    self.meta = [_tileMap layerNamed:@"Meta"];              //Meta tiles determine whether object is obstacle or consumable
    _meta.visible = NO;                                     //Ensure meta tiles are hidden!
    
    CCTMXObjectGroup *objects = [_tileMap objectGroupNamed:@"Objects"];
    NSAssert(objects != nil, @"'Objects' object group not found");
    
    //Set up player spawn point
    NSMutableDictionary *spawnPoint = [objects objectNamed:@"SpawnPoint"];        
    NSAssert(spawnPoint != nil, @"SpawnPoint object not found");
    playerSpawnX = [[spawnPoint valueForKey:@"x"] intValue];
    playerSpawnY = [[spawnPoint valueForKey:@"y"] intValue];
    
    NSMutableDictionary *enemySpawn = [objects objectNamed:@"EnemySpawn"];        
    NSAssert(enemySpawn != nil, @"EnemySpawn object not found");
    enemySpawnX = [[enemySpawn valueForKey:@"x"] intValue];
    enemySpawnY = [[enemySpawn valueForKey:@"y"] intValue];
    enemySpawnPos1 = ccp(enemySpawnX,enemySpawnY);
    
    NSMutableDictionary *enemySpawn2 = [objects objectNamed:@"EnemySpawn2"];        
    NSAssert(enemySpawn2 != nil, @"EnemySpawn2 object not found");
    enemySpawnX2 = [[enemySpawn2 valueForKey:@"x"] intValue];
    enemySpawnY2 = [[enemySpawn2 valueForKey:@"y"] intValue];


    NSMutableDictionary *patrolPoint1 = [objects objectNamed:@"PatrolPoint1"];        
    NSAssert(patrolPoint1 != nil, @"PatrolPoint1 object not found");
    patrolPointX1 = [[patrolPoint1 valueForKey:@"x"] intValue];
    patrolPointY1 = [[patrolPoint1 valueForKey:@"y"] intValue];
    enemy2_patrolPoint1 = ccp(patrolPointX1,patrolPointY1);
    
    
    NSMutableDictionary *enemySpawn3 = [objects objectNamed:@"EnemySpawn3"];        
    NSAssert(enemySpawn3 != nil, @"EnemySpawn3 object not found");
    enemySpawnX3 = [[enemySpawn3 valueForKey:@"x"] intValue];
    enemySpawnY3 = [[enemySpawn3 valueForKey:@"y"] intValue];
    
    NSMutableDictionary *PatrolPoint1_enemy3 = [objects objectNamed:@"PatrolPoint1_enemy3"];        
    NSAssert(PatrolPoint1_enemy3 != nil, @"PatrolPoint1_enemy3 object not found");
    patrolPointX1_enemy3 = [[PatrolPoint1_enemy3 valueForKey:@"x"] intValue];
    patrolPointY1_enemy3 = [[PatrolPoint1_enemy3 valueForKey:@"y"] intValue];
    enemy3_patrolPoint1 = ccp(patrolPointX1_enemy3,patrolPointY1_enemy3);
    
    
    NSMutableDictionary *enemySpawn4 = [objects objectNamed:@"EnemySpawn4"];        
    NSAssert(enemySpawn4 != nil, @"EnemySpawn4 object not found");
    enemySpawnX4 = [[enemySpawn4 valueForKey:@"x"] intValue];
    enemySpawnY4 = [[enemySpawn4 valueForKey:@"y"] intValue];
    
    NSMutableDictionary *PatrolPoint1_enemy4 = [objects objectNamed:@"PatrolPoint1_enemy4"];        
    NSAssert(PatrolPoint1_enemy4 != nil, @"PatrolPoint1_enemy4 object not found");
    patrolPointX1_enemy4 = [[PatrolPoint1_enemy4 valueForKey:@"x"] intValue];
    patrolPointY1_enemy4 = [[PatrolPoint1_enemy4 valueForKey:@"y"] intValue];
    
    NSMutableDictionary *enemySpawn5 = [objects objectNamed:@"EnemySpawn5"];        
    NSAssert(enemySpawn5 != nil, @"EnemySpawn5 object not found");
    enemySpawnX5 = [[enemySpawn5 valueForKey:@"x"] intValue];
    enemySpawnY5 = [[enemySpawn5 valueForKey:@"y"] intValue];
    
    NSMutableDictionary *PatrolPoint1_enemy5 = [objects objectNamed:@"PatrolPoint1_enemy5"];        
    NSAssert(PatrolPoint1_enemy5 != nil, @"PatrolPoint1_enemy5 object not found");
    patrolPointX1_enemy5 = [[PatrolPoint1_enemy5 valueForKey:@"x"] intValue];
    patrolPointY1_enemy5 = [[PatrolPoint1_enemy5 valueForKey:@"y"] intValue];
    
    
    
    
    CGPoint patrolTileCoord = [self tileCoordForPosition:CGPointMake(enemySpawnX2, enemySpawnY2)];
    self.startPatrolX = patrolTileCoord.x;
    self.startPatrolY = patrolTileCoord.y;
    CGPoint patrolTileCoord1 = [self tileCoordForPosition:CGPointMake(patrolPointX1, patrolPointY1)];
    self.endPatrolX = patrolTileCoord1.x;
    self.endPatrolY = patrolTileCoord1.y;
    
    
    CGPoint patrolTileCoord1_enemy3 = [self tileCoordForPosition:CGPointMake(enemySpawnX3, enemySpawnY3)];
    self.startPatrolX_enemy3 = patrolTileCoord1_enemy3.x;
    self.startPatrolY_enemy3 = patrolTileCoord1_enemy3.y;
    CGPoint patrolTileCoord2_enemy3 = [self tileCoordForPosition:CGPointMake(patrolPointX1_enemy3, patrolPointY1_enemy3)];
    self.endPatrolX_enemy3 = patrolTileCoord2_enemy3.x;
    self.endPatrolY_enemy3 = patrolTileCoord2_enemy3.y;
    
    CGPoint patrolTileCoord1_enemy4 = [self tileCoordForPosition:CGPointMake(enemySpawnX4, enemySpawnY4)];
    self.startPatrolX_enemy4 = patrolTileCoord1_enemy4.x;
    self.startPatrolY_enemy4 = patrolTileCoord1_enemy4.y;
    CGPoint patrolTileCoord2_enemy4 = [self tileCoordForPosition:CGPointMake(patrolPointX1_enemy4, patrolPointY1_enemy4)];
    self.endPatrolX_enemy4 = patrolTileCoord2_enemy4.x;
    self.endPatrolY_enemy4 = patrolTileCoord2_enemy4.y;
    
    CGPoint patrolTileCoord1_enemy5 = [self tileCoordForPosition:CGPointMake(enemySpawnX5, enemySpawnY5)];
    self.startPatrolX_enemy5 = patrolTileCoord1_enemy5.x;
    self.startPatrolY_enemy5 = patrolTileCoord1_enemy5.y;
    CGPoint patrolTileCoord2_enemy5 = [self tileCoordForPosition:CGPointMake(patrolPointX1_enemy5, patrolPointY1_enemy5)];
    self.endPatrolX_enemy5 = patrolTileCoord2_enemy5.x;
    self.endPatrolY_enemy5 = patrolTileCoord2_enemy5.y;
    
    
    
    
    
    //Starting from enemy pos:
    CGPoint point = [self tileCoordForPosition:CGPointMake(enemySpawnX, enemySpawnY)];
	self.startX = point.x;
	self.startY = point.y;
    
    //To player pos:
    CGPoint point1 = [self tileCoordForPosition:CGPointMake(playerSpawnX, playerSpawnY)];
	self.endX = point1.x;
	self.endY = point1.y;
    
    for (int c = 0; c < TILE_COLS_lv2; c++) {
        for (int r = 0; r < TILE_ROWS_lv2; r++) {
            if (c == self.startX && r == self.startY) {
				tileArray[c][r] = TILE_START;
				CCLOG(@"Enemy Sprite Pos: %d, %d", c, r);
			}
            else if (c == self.endX && r == self.endY) {
				CCLOG(@"Player Pos: at %d, %d", c, r);
				tileArray[c][r] = TILE_FINISH;
			}
			else if ([self isWall:[self tilePositionForCoord:CGPointMake((float) c, (float) r)]]) {
				tileArray[c][r] = TILE_WALL;
			}
			else {
				tileArray[c][r] = TILE_OPEN;
			}
        }
    }
    [self addChild:_tileMap z:-100 tag:99];
    
    CCLOG(@"Tiled Map Loaded.");
}


#pragma mark get level
//Sets default level to load in the init class - will be the first game level. Currently test map for dev purposes. 
+(NSString*) getDefaultLevel{
    return @"Level_2.tmx";  //replace with "level 1" etc
}

#pragma mark - positions
- (CGPoint)tileCoordForPosition:(CGPoint)position {
    int x = position.x / _tileMap.tileSize.width;
    int y = ((_tileMap.mapSize.height * _tileMap.tileSize.height) - position.y) / _tileMap.tileSize.height;
    return ccp(x, y);
}

- (CGPoint)positionForTileCoord:(CGPoint)tileCoord {
    int x = (tileCoord.x * _tileMap.tileSize.width) + _tileMap.tileSize.width/2;
    int y = (_tileMap.mapSize.height * _tileMap.tileSize.height) - (tileCoord.y * _tileMap.tileSize.height) - _tileMap.tileSize.height/2;
    return ccp(x, y);
}

- (CGPoint)tilePositionForCoord:(CGPoint)coord {
    int x = (coord.x * _tileMap.tileSize.width) + (_tileMap.tileSize.width / 2);
    int y = (coord.y * _tileMap.tileSize.height) + (_tileMap.tileSize.height / 2);
    return ccp(x, y);
}

// Determines if the cell at the given position on the tilemap is a wall
-(BOOL) isWall:(CGPoint) position {
	CGPoint tileCoord = [self tileCoordForPosition:position];
	int tileGid = [_meta tileGIDAt:tileCoord];
	if (tileGid) {
        //tileMap not _tileMap??????
		NSDictionary *properties = [_tileMap propertiesForGID:tileGid];
		if (properties) {
			NSString *propertyValue = [properties valueForKey:@"Collidable"];
			if (propertyValue && [propertyValue compare:@"True"] == NSOrderedSame) {
				return YES;
			}
		}
	}
	return NO;
}


//Flip tile array
-(void) flipTileArray {
	unsigned char temp[TILE_COLS_lv2][TILE_ROWS_lv2]; 
    
	int destRow = TILE_ROWS_lv2-1;
	int srcRow = 0;
	
	//Store the original values in a temp array
	while (destRow >= 0) {
		for (int x = 0; x < TILE_COLS_lv2; x++) {
			temp[x][destRow] = tileArray[x][srcRow];
		}
		srcRow++;
		destRow--;
	}
    
	//Flip them
	for (int r = 0; r < TILE_ROWS_lv2; r++) {
		for (int c = 0; c < TILE_COLS_lv2; c++) {
			tileArray[c][r] = temp[c][r];
		}
	}
}

#pragma mark create path
//Generate path between player and enemy and move enemy sprite along path
//Updates every 3 seconds (as player may move!)
-(void) createPath:(ccTime)dt {
	// Clear any old results;
	[self clear:nil];
	
	// Flip the tileArray (path algorithm expects origin to be upper left)
	[self flipTileArray];
	
	// Find the path
	BOOL pathFound = [self findPath: self.startX :self.startY :self.endX :self.endY]; 
        
	//Flip tileArray back so when we draw the path the objects will be in the correct location on the map
	[self flipTileArray];
    
	if (pathFound) {
		//CCLOG(@"Path found!");
        [self moveOnPath];
	}
	else {
		CCLOG(@"Path NOT found!!!");
        [enemy1 changeState:kStateIdle];
        return;    
	}
    
}


//Creates enemy sprite patrol paths
//Doesn't need to update as these are pre-defined routes
//ccTime - remove if not working? 
-(void)patrolPaths:(ccTime)dt{
    audioCounter = 0;
    int pat_x1,pat_y1;
    CCMoveTo *patrolAction;
    CCMoveTo *returnPatrolAction;
    id moveSequence = nil;
    id returnSequence = nil;

    BOOL pathFound,patrolOut;
    
    if (calcPatrolPath == 1){
        patrolOut = TRUE;
        patrolCounter = 0;
        patrolPathX1 = [NSMutableArray array];
        patrolPathY1 = [NSMutableArray array];
        
        [self clear:nil];
                
        [self flipTileArray];
        
        //Create first section of route
        pathFound = [self findPath:self.startPatrolX :self.startPatrolY :self.endPatrolX :self.endPatrolY];

        [self flipTileArray];
        
        if (pathFound){
            CCLOG(@"Patrol path found");
//            calcPatrolPath = FALSE;
            calcPatrolPath++;
            //Reverse order of contents in Arrays (calculates path backwards):
            NSUInteger i = 0;
            NSUInteger j = [patrolPathX1 count] - 1;
            while (i < j) {
                [patrolPathX1 exchangeObjectAtIndex:i withObjectAtIndex:j];
                [patrolPathY1 exchangeObjectAtIndex:i withObjectAtIndex:j];
                i++;
                j--;
            }
            
            int pat_x2, pat_y2; 
            if (patrolOut == TRUE){
                for (int x = 0; x<[patrolPathX1 count]; x++){
                    pat_x1=[[patrolPathX1 objectAtIndex:x]intValue];
                    pat_y1=[[patrolPathY1 objectAtIndex:x]intValue];
                    
                    if ([patrolPathX1 count]==x){
                        pat_x2 = [[patrolPathX1 objectAtIndex:[patrolPathX1 count]-1]intValue];
                        pat_y2 = [[patrolPathY1 objectAtIndex:[patrolPathX1 count]-1]intValue];
                    }
                    else if (x==0){
                    pat_x2 = [[patrolPathX1 objectAtIndex:[patrolPathX1 count]-1]intValue];
                    pat_y2 = [[patrolPathY1 objectAtIndex:[patrolPathX1 count]-1]intValue];
                    }
                    else {
                        pat_x2 = [[patrolPathX1 objectAtIndex:[patrolPathX1 count]-x]intValue];
                        pat_y2 = [[patrolPathY1 objectAtIndex:[patrolPathX1 count]-x]intValue];
                    }
                    
                    
                    patrolAction = [CCMoveTo actionWithDuration:0.5 position:[self positionForTileCoord:CGPointMake((float) pat_x1, (float) pat_y1)]];
                    returnPatrolAction = [CCMoveTo actionWithDuration:0.5 position:[self positionForTileCoord:CGPointMake((float) pat_x2, (float) pat_y2)]];
                    
                    if (moveSequence != nil) {
                        moveSequence = [CCSequence actionOne: moveSequence two: patrolAction];
                    } else {
                        moveSequence = patrolAction; //the first action
                    }
                    
                    if (returnSequence!=nil){
                        returnSequence = [CCSequence actionOne: returnSequence two: returnPatrolAction];
                    }
                    
                    else{
                        returnSequence = returnPatrolAction;
                    }
                    
                    
                }
 
                [enemy2 changeState:kStateWalkingDown];
                
                CCSequence *patrolSeq = [CCSequence actions: moveSequence, returnSequence, nil];
                [enemy2 runAction:[CCRepeatForever actionWithAction:patrolSeq]];
            }
            
            else if (patrolOut == FALSE){
                CCLOG(@"false");
                

            }
            else{
                CCLOG(@"Patrol Path not found");
                [enemy2 changeState:kStateIdle];
                return;
            }

        }
    }
    int pat_x1_enemy3,pat_y1_enemy3;
    int pat_x2_enemy3, pat_y2_enemy3;
    CCMoveTo *patrolAction_enemy3;
    CCMoveTo *returnPatrolAction_enemy3;
    id moveSequence_enemy3 = nil;
    id returnSequence_enemy3 = nil;
    
    if (calcPatrolPath == 2){
        patrolPathX1_enemy3 = [NSMutableArray array];
        patrolPathY1_enemy3 = [NSMutableArray array];
        
        [self clear:nil];
        
        
        [self flipTileArray];
        
        //Create first section of route
        pathFound = [self findPath:self.startPatrolX_enemy3 :self.startPatrolY_enemy3 :self.endPatrolX_enemy3 :self.endPatrolY_enemy3];

        [self flipTileArray];
        
        if (pathFound){
            CCLOG(@"Patrol path found - enemy 3");
            calcPatrolPath++;

            //Reverse order of contents in Arrays (calculates path backwards):
            NSUInteger i = 0;
            NSUInteger j = [patrolPathX1_enemy3 count] - 1;
            while (i < j) {
                [patrolPathX1_enemy3 exchangeObjectAtIndex:i withObjectAtIndex:j];
                [patrolPathY1_enemy3 exchangeObjectAtIndex:i withObjectAtIndex:j];
                i++;
                j--;
            }
                for (int x = 0; x<[patrolPathX1_enemy3 count]; x++){
                    pat_x1_enemy3=[[patrolPathX1_enemy3 objectAtIndex:x]intValue];
                    pat_y1_enemy3=[[patrolPathY1_enemy3 objectAtIndex:x]intValue];
                    
                    if ([patrolPathX1_enemy3 count]==x){
                        pat_x2_enemy3 = [[patrolPathX1_enemy3 objectAtIndex:[patrolPathX1_enemy3 count]-1]intValue];
                        pat_y2_enemy3 = [[patrolPathY1_enemy3 objectAtIndex:[patrolPathX1_enemy3 count]-1]intValue];
                    }
                    else if (x==0){
                        pat_x2_enemy3 = [[patrolPathX1_enemy3 objectAtIndex:[patrolPathX1_enemy3 count]-1]intValue];
                        pat_y2_enemy3 = [[patrolPathY1_enemy3 objectAtIndex:[patrolPathX1_enemy3 count]-1]intValue];
                    }
                    else {
                        pat_x2_enemy3 = [[patrolPathX1_enemy3 objectAtIndex:[patrolPathX1_enemy3 count]-x]intValue];
                        pat_y2_enemy3 = [[patrolPathY1_enemy3 objectAtIndex:[patrolPathX1_enemy3 count]-x]intValue];
                    }
                    
                    patrolAction_enemy3 = [CCMoveTo actionWithDuration:0.5 position:[self positionForTileCoord:CGPointMake((float) pat_x1_enemy3, (float) pat_y1_enemy3)]];
                    returnPatrolAction_enemy3 = [CCMoveTo actionWithDuration:0.5 position:[self positionForTileCoord:CGPointMake((float) pat_x2_enemy3, (float) pat_y2_enemy3)]];
                    
                    if (moveSequence_enemy3 != nil) {
                        moveSequence_enemy3 = [CCSequence actionOne: moveSequence_enemy3 two: patrolAction_enemy3];
                    } else {
                        moveSequence_enemy3 = patrolAction_enemy3; //the first action
                    }
                    
                    if (returnSequence_enemy3!=nil){
                        returnSequence_enemy3 = [CCSequence actionOne: returnSequence_enemy3 two: returnPatrolAction_enemy3];
                    }
                    
                    else{
                        returnSequence_enemy3 = returnPatrolAction_enemy3;
                    }
                }
                [enemy3 changeState:kStateWalkingDown];
                
                CCSequence *patrolSeq_enemy3 = [CCSequence actions: moveSequence_enemy3, returnSequence_enemy3, nil];
                [enemy3 runAction:[CCRepeatForever actionWithAction:patrolSeq_enemy3]];
            }
            
            else{
                CCLOG(@"Patrol Path not found - enemy 3");
                [enemy3 changeState:kStateIdle];
                return;
            }
    }
    
    int pat_x1_enemy4,pat_y1_enemy4;
    int pat_x2_enemy4, pat_y2_enemy4;
    CCMoveTo *patrolAction_enemy4;
    CCMoveTo *returnPatrolAction_enemy4;
    id moveSequence_enemy4 = nil;
    id returnSequence_enemy4 = nil;
    
    if (calcPatrolPath == 3){
        patrolPathX1_enemy4 = [NSMutableArray array];
        patrolPathY1_enemy4 = [NSMutableArray array];
        
        [self clear:nil];
        
        
        [self flipTileArray];
        
        //Create first section of route
        pathFound = [self findPath:self.startPatrolX_enemy4 :self.startPatrolY_enemy4 :self.endPatrolX_enemy4 :self.endPatrolY_enemy4];
        
        [self flipTileArray];
        
        if (pathFound){
            CCLOG(@"Patrol path found - enemy 4");
            calcPatrolPath++;
            
            //Reverse order of contents in Arrays (calculates path backwards):
            NSUInteger i = 0;
            NSUInteger j = [patrolPathX1_enemy4 count] - 1;
            while (i < j) {
                [patrolPathX1_enemy4 exchangeObjectAtIndex:i withObjectAtIndex:j];
                [patrolPathY1_enemy4 exchangeObjectAtIndex:i withObjectAtIndex:j];
                i++;
                j--;
            }
            for (int x = 0; x<[patrolPathX1_enemy4 count]; x++){
                pat_x1_enemy4=[[patrolPathX1_enemy4 objectAtIndex:x]intValue];
                pat_y1_enemy4=[[patrolPathY1_enemy4 objectAtIndex:x]intValue];
                
                if ([patrolPathY1_enemy4 count]==x){
                    pat_x2_enemy4 = [[patrolPathX1_enemy4 objectAtIndex:[patrolPathX1_enemy4 count]-1]intValue];
                    pat_y2_enemy4 = [[patrolPathY1_enemy4 objectAtIndex:[patrolPathX1_enemy4 count]-1]intValue];
                }
                else if (x==0){
                    pat_x2_enemy4 = [[patrolPathX1_enemy4 objectAtIndex:[patrolPathX1_enemy4 count]-1]intValue];
                    pat_y2_enemy4 = [[patrolPathY1_enemy4 objectAtIndex:[patrolPathX1_enemy4 count]-1]intValue];
                }
                else {
                    pat_x2_enemy4 = [[patrolPathX1_enemy4 objectAtIndex:[patrolPathX1_enemy4 count]-x]intValue];
                    pat_y2_enemy4 = [[patrolPathY1_enemy4 objectAtIndex:[patrolPathX1_enemy4 count]-x]intValue];
                }
                
                patrolAction_enemy4 = [CCMoveTo actionWithDuration:0.5 position:[self positionForTileCoord:CGPointMake((float) pat_x1_enemy4, (float) pat_y1_enemy4)]];
                returnPatrolAction_enemy4 = [CCMoveTo actionWithDuration:0.5 position:[self positionForTileCoord:CGPointMake((float) pat_x2_enemy4, (float) pat_y2_enemy4)]];
                
                if (moveSequence_enemy4 != nil) {
                    moveSequence_enemy4 = [CCSequence actionOne: moveSequence_enemy4 two: patrolAction_enemy4];
                } else {
                    moveSequence_enemy4 = patrolAction_enemy4; //the first action
                }
                
                if (returnSequence_enemy4!=nil){
                    returnSequence_enemy4 = [CCSequence actionOne: returnSequence_enemy4 two: returnPatrolAction_enemy4];
                }
                
                else{
                    returnSequence_enemy4 = returnPatrolAction_enemy4;
                }
            }
            [enemy4 changeState:kStateWalkingDown];
            
            CCSequence *patrolSeq_enemy4 = [CCSequence actions: moveSequence_enemy4, returnSequence_enemy4, nil];
            [enemy4 runAction:[CCRepeatForever actionWithAction:patrolSeq_enemy4]];
        }
        
        else{
            CCLOG(@"Patrol Path not found - enemy 4");
            [enemy4 changeState:kStateIdle];
            return;
        }
    }
    int pat_x1_enemy5,pat_y1_enemy5;
    int pat_x2_enemy5, pat_y2_enemy5;
    CCMoveTo *patrolAction_enemy5;
    CCMoveTo *returnPatrolAction_enemy5;
    id moveSequence_enemy5 = nil;
    id returnSequence_enemy5 = nil;
    
    if (calcPatrolPath == 4){
        patrolPathX1_enemy5 = [NSMutableArray array];
        patrolPathY1_enemy5 = [NSMutableArray array];
        
        [self clear:nil];
        
        
        [self flipTileArray];
        
        //Create first section of route
        pathFound = [self findPath:self.startPatrolX_enemy5 :self.startPatrolY_enemy5 :self.endPatrolX_enemy5 :self.endPatrolY_enemy5];
        
        [self flipTileArray];
        
        if (pathFound){
            CCLOG(@"Patrol path found - enemy 5");
            calcPatrolPath++;
            
            //Reverse order of contents in Arrays (calculates path backwards):
            NSUInteger i = 0;
            NSUInteger j = [patrolPathX1_enemy5 count] - 1;
            while (i < j) {
                [patrolPathX1_enemy5 exchangeObjectAtIndex:i withObjectAtIndex:j];
                [patrolPathY1_enemy5 exchangeObjectAtIndex:i withObjectAtIndex:j];
                i++;
                j--;
            }
            for (int x = 0; x<[patrolPathX1_enemy5 count]; x++){
                pat_x1_enemy5=[[patrolPathX1_enemy5 objectAtIndex:x]intValue];
                pat_y1_enemy5=[[patrolPathY1_enemy5 objectAtIndex:x]intValue];
                
                if ([patrolPathX1_enemy5 count]==x){
                    pat_x2_enemy5 = [[patrolPathX1_enemy5 objectAtIndex:[patrolPathX1_enemy5 count]-1]intValue];
                    pat_y2_enemy5 = [[patrolPathY1_enemy5 objectAtIndex:[patrolPathX1_enemy5 count]-1]intValue];
                }
                else if (x==0){
                    pat_x2_enemy5 = [[patrolPathX1_enemy5 objectAtIndex:[patrolPathX1_enemy5 count]-1]intValue];
                    pat_y2_enemy5 = [[patrolPathY1_enemy5 objectAtIndex:[patrolPathX1_enemy5 count]-1]intValue];
                }
                else {
                    pat_x2_enemy5 = [[patrolPathX1_enemy5 objectAtIndex:[patrolPathX1_enemy5 count]-x]intValue];
                    pat_y2_enemy5 = [[patrolPathY1_enemy5 objectAtIndex:[patrolPathX1_enemy5 count]-x]intValue];
                }
                
                patrolAction_enemy5 = [CCMoveTo actionWithDuration:0.5 position:[self positionForTileCoord:CGPointMake((float) pat_x1_enemy5, (float) pat_y1_enemy5)]];
                returnPatrolAction_enemy5 = [CCMoveTo actionWithDuration:0.5 position:[self positionForTileCoord:CGPointMake((float) pat_x2_enemy5, (float) pat_y2_enemy5)]];
                
                if (moveSequence_enemy5 != nil) {
                    moveSequence_enemy5 = [CCSequence actionOne: moveSequence_enemy5 two: patrolAction_enemy5];
                } else {
                    moveSequence_enemy5 = patrolAction_enemy5; //the first action
                }
                
                if (returnSequence_enemy5!=nil){
                    returnSequence_enemy5 = [CCSequence actionOne: returnSequence_enemy5 two: returnPatrolAction_enemy5];
                }
                
                else{
                    returnSequence_enemy5 = returnPatrolAction_enemy5;
                }
            }
            
            if (pat_x1_enemy5>pat_x2_enemy5){
                [enemy5 changeState:kStateWalkingUp];

            }
            if (pat_x1_enemy5<pat_x2_enemy5){
                [enemy5 changeState:kStateWalkingDown];
                
            }
            else{
                [enemy5 changeState:kStateWalkingRight];
            }
             
            CCSequence *patrolSeq_enemy5 = [CCSequence actions: moveSequence_enemy5, returnSequence_enemy5, nil];
            [enemy5 runAction:[CCRepeatForever actionWithAction:patrolSeq_enemy5]];
            patrolPathsToGenerate = FALSE;
            pathCheck++;
        }
        
        else{
            CCLOG(@"Patrol Path not found - enemy 5");
            [enemy5 changeState:kStateIdle];
            return;
        }
    }
}



-(void)moveOnPath{
    //If movement arrays are empty, return:
    if ([movementPathX count]<=1){ 
        CCLOG(@"Enemy movement arrays empty");
        [enemy1 changeState:kStateIdle];
        return; 
    }

    //Reverse order of contents in Arrays (calculates path backwards):
    NSUInteger i = 0;
    NSUInteger j = [movementPathX count] - 1;
    while (i < j) {
        [movementPathX exchangeObjectAtIndex:i withObjectAtIndex:j];
        [movementPathY exchangeObjectAtIndex:i withObjectAtIndex:j];
        i++;
        j--;
    }
    
    int x1,y1;  //For next position co-ords
    int x2,y2;  //For next tile check
    int x3,y3;  //For next, next tile check
    id moveAction, moveAction2, moveAction3;
    CCAction *walkingAction;
    
//    for (int x = 0; x<1; x++){ 
        if ([movementPathX count]==2){  //Move at hop of 2
            x1=[[movementPathX objectAtIndex:0]intValue];
            y1=[[movementPathY objectAtIndex:0]intValue];
            moveAction = [CCMoveTo actionWithDuration:1.5 position:[self positionForTileCoord:CGPointMake((float) x1, (float) y1)]];
            
            x2=[[movementPathX objectAtIndex:1]intValue];
            y2=[[movementPathY objectAtIndex:1]intValue];
            moveAction2 = [CCMoveTo actionWithDuration:1.5 position:[self positionForTileCoord:CGPointMake((float) x2, (float) y2)]];
            
            walkingAction = [CCSequence actions:moveAction,moveAction2, nil];
            
        }
        
        if ([movementPathX count]>=3){  //Move at hop of 3
            x1=[[movementPathX objectAtIndex:0]intValue];
            y1=[[movementPathY objectAtIndex:0]intValue];
            moveAction = [CCMoveTo actionWithDuration:1.0 position:[self positionForTileCoord:CGPointMake((float) x1, (float) y1)]];
            
            x2=[[movementPathX objectAtIndex:1]intValue];
            y2=[[movementPathY objectAtIndex:1]intValue];
            moveAction2 = [CCMoveTo actionWithDuration:1.0 position:[self positionForTileCoord:CGPointMake((float) x2, (float) y2)]];
            
            x3=[[movementPathX objectAtIndex:2]intValue];
            y3=[[movementPathY objectAtIndex:2]intValue];
            moveAction3 = [CCMoveTo actionWithDuration:1.0 position:[self positionForTileCoord:CGPointMake((float) x3, (float) y3)]];
            
            walkingAction = [CCSequence actions:moveAction, moveAction2, moveAction3, nil];  
        }        
        
        //Change direction of enemy sprite
        if (x1>x2){
            [enemy1 changeState:kStateWalkingLeft];
        }
        
        else if (x1<x2){
            [enemy1 changeState:kStateWalkingRight];
            
        }
        
        else if (y1>y2){
            [enemy1 changeState:kStateWalkingUp];
        }
        
        else if (y1<y2){
            [enemy1 changeState:kStateWalkingDown];
        }
        
        
    [enemy1 runAction:walkingAction];


}


//Unmark discovered cells in the array
-(void) clear:(id) sender {
	int x,y;
	for(x=0;x<TILE_COLS_lv2;x++) {
		for(y=0;y<TILE_ROWS_lv2;y++) {
			if(tileArray[x][y] == TILE_MARKED)
				tileArray[x][y] = TILE_OPEN;
		}
	}
	//Create an array of nodes we need to remove from the parent
	//Iterate the list and mark them
	NSMutableArray *nodesToCleanup = [[NSMutableArray alloc] initWithCapacity:50];
	//Flag them for removal
	for (CCNode *node in self.children) {
		if (node.tag == TILE_TAG) {
			[nodesToCleanup addObject:node];
		}
	}
	//Now remove nodes
	for (CCNode *node in nodesToCleanup) {
		[node removeFromParentAndCleanup:YES];
	}
}

//Return whether a space is blocked
-(BOOL)spaceIsBlocked:(int)x :(int)y; {
	if(tileArray[x][y] == TILE_WALL)
		return YES;
	else
		return NO;
}

//Find a given node in array with specific x,y val:
-(PathNode *)nodeInArray:(NSMutableArray *)a withX:(int)x Y:(int)y{
    NSEnumerator *e = [a objectEnumerator];
    PathNode *n;
    if(e){
		while((n = [e nextObject])) {
			if((n->nodeX == x) && (n->nodeY == y))
			{
				return n;
			}
        }
    }
    return nil;
}

//Calculates node in array with lowest cost
-(PathNode *)lowestCostNodeInArray:(NSMutableArray*)openList{
    PathNode *n, *lowest;
    lowest = nil;
    
    NSEnumerator *enumerator = [openList objectEnumerator];
    
    if (enumerator){
		while((n = [enumerator nextObject])) {
			if(lowest == nil)
			{
				lowest = n;
			}
            else
            {
                if (n->cost < lowest -> cost){
                    lowest = n;
                }
            }
        }
        return lowest;
    }
    return nil;
}

#pragma mark A* path finder
//A* Path Finder - detects path between enemy and player sprites whilst avoiding walls
-(BOOL)findPath:(int)startingX :(int)startingY :(int)endingX :(int)endingY {    
	int x,y;
	int newX,newY;
	int currentX,currentY;
    //CCLOG(@"Starting: %d,%d",startingX,startingY);
	NSMutableArray *openList, *closedList;
    
    if ((startingX==endingX) && (startingY==endingY)){
        CCLOG(@"Already at destination!");
        return NO;
    }
    
    openList = [NSMutableArray array];
    closedList = [NSMutableArray array];
    
    movementPathX = [NSMutableArray array];
    movementPathY = [NSMutableArray array];
    
    PathNode *currentNode = nil;
    PathNode *aNode = nil;
    PathNode *startNode = [PathNode node];
    
    startNode->nodeX = startingX;
    startNode->nodeY = startingY;
    startNode->parentNode = nil;
    startNode->cost = 0;
    
    [openList addObject:startNode];
    
    while ([openList count]){
        currentNode = [self lowestCostNodeInArray:openList];
        
        if ((currentNode->nodeX == endingX) && (currentNode->nodeY == endingY)){    //Path has been found            
            //Trace the path:
            aNode = currentNode->parentNode;
            while(aNode->parentNode!=nil){
                tileArray[aNode->nodeX][aNode->nodeY] = TILE_MARKED;  
                //Add path coordinates to arrays (used to move Sprites along paths)
                if (calcPatrolPath == 1){
                    [patrolPathX1 addObject:[NSNumber numberWithInteger:aNode->nodeX]];
                    [patrolPathY1 addObject:[NSNumber numberWithInteger:aNode->nodeY]];

                }
                if (calcPatrolPath == 2){
                    [patrolPathX1_enemy3 addObject:[NSNumber numberWithInteger:aNode->nodeX]];
                    [patrolPathY1_enemy3 addObject:[NSNumber numberWithInteger:aNode->nodeY]];
                }
                if (calcPatrolPath == 3){
                    [patrolPathX1_enemy4 addObject:[NSNumber numberWithInteger:aNode->nodeX]];
                    [patrolPathY1_enemy4 addObject:[NSNumber numberWithInteger:aNode->nodeY]];

                }
                if (calcPatrolPath == 4){
                    [patrolPathX1_enemy5 addObject:[NSNumber numberWithInteger:aNode->nodeX]];
                    [patrolPathY1_enemy5 addObject:[NSNumber numberWithInteger:aNode->nodeY]];
                }
                else{
                    [movementPathX addObject:[NSNumber numberWithInteger:aNode->nodeX]];
                    [movementPathY addObject:[NSNumber numberWithInteger:aNode->nodeY]];
                }
                aNode = aNode->parentNode;                
            }
//            calcPatrolPath = FALSE;
        
            return YES;
        }
        else{
            [closedList addObject:currentNode];
            [openList removeObject:currentNode];
            
            currentX = currentNode->nodeX;
            currentY = currentNode->nodeY;
            
            //Check all surrounding tiles:
			for(y=-1;y<=1;y++){
                newY = currentY+y;
				for(x=-1;x<=1;x++){
                    newX = currentX+x;
					if(y || x){
                        //Bounds check 
						if((newX>=0)&&(newY>=0)&&(newX<TILE_COLS_lv2)&&(newY<TILE_ROWS_lv2)){
                            //Prevent diagonal checks
                            if ((!(y==-1 && x==-1) && !(y==-1 && x==1)&& !(y== 1 && x== -1) && !(y==1 && x==1)) || self.allowDiags == YES) {
                                if(![self nodeInArray: openList withX: newX Y:newY]){
                                    if(![self nodeInArray: closedList withX: newX Y:newY])
									{
										if(![self spaceIsBlocked: newX :newY])
										{
                                            aNode = [PathNode node];
											aNode->nodeX = newX;
											aNode->nodeY = newY;
											aNode->parentNode = currentNode;
											aNode->cost = currentNode->cost + 1;
                                            
                                            //Compute cost:
                                            aNode->cost += (abs((newX) - endingX) + abs((newY) - endingY));
                                            
                                            [openList addObject: aNode];
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return NO;
}


//Update Method
//Constantly checks for collisions/warps 
//Maintains camera focused on player sprite position
//Checks whether start/end points of path have changed
#pragma mark - 
#pragma mark - update
-(void) update: (ccTime)deltaTime{
//    isCollision=FALSE;
    if (pathCheck == 0){
        [self schedule:@selector(patrolPaths:)interval:1];

    }
    if (pathCheck == 1){
        [self schedule:@selector(createPath:)interval:3];
        pathCheck++;
    }
    
    
    [self setViewpointCenter:playerX.position]; //constantly moves camera according to player position 
    

    if (([platformType isEqualToString:@"Simulator"])||([platformType isEqualToString:@"iPad"])||([platformType isEqualToString:@"iPad 2 (WiFi)"])||([platformType isEqualToString:@"iPad 2 (GSM)"])||([platformType isEqualToString:@"iPad 2 (CDMA)"])){
//        spotLight.position = ccp(playerX.position.x+538,playerX.position.y+785); 
        fogCoord = [self convertToWorldSpace: ccp(playerX.position.x,playerX.position.y)];

    }
    
//    [self setViewpointCenter:enemy1.position];
//    [self setViewpointCenter:enemy2.position];
//    [self setViewpointCenter:enemy5.position];
    
    //Updates player and enemy positions for path finder:
    CGPoint point = [self tileCoordForPosition:CGPointMake(enemy1.position.x, enemy1.position.y)];
	self.startX = point.x;
	self.startY = point.y;
    CGPoint point1 = [self tileCoordForPosition:CGPointMake(playerX.position.x, playerX.position.y)];
	self.endX = point1.x;
	self.endY = point1.y;
    
    //Constantly checking for obstacles/warps:
    tileCoord = [self tileCoordForPosition:playerX.position];
    tileCoord1 = [self tileCoordForPosition:enemy1.position];
    
    int tileGid = [_meta tileGIDAt:tileCoord];
    
    if (tileGid) {
        NSDictionary *properties = [_tileMap propertiesForGID:tileGid];
        if (properties) {
            //Collision
            NSString *collision = [properties valueForKey:@"Collidable"];
            if (collision && [collision compare:@"True"] == NSOrderedSame) {
                CCLOG(@"Collision (update method)");
                if (audioCounter == 0){
                    [AudioManager collisionSound];
                    audioCounter++;
                }
                [playerX changeState:kStateCollision];
                return;
            }
            //Warp - when player steps on "warp" meta tile, load new scene
            NSString *warp = [properties valueForKey:@"Warp"];
            if (warp && [warp compare:@"1"] == NSOrderedSame) {
                CCLOG(@"Level Complete! (WARP)");          
                [AudioManager levelComplete];
                [[SceneManager sharedSceneManager] runSceneWithID:kLevelCompleteScene];     //Objective reached, load "level complete" scene
                
            }
        }
    }
}

@end

